package com.immediatus.engine.input.sensor.orientation;

import android.hardware.SensorManager;
import android.view.Surface;
import com.immediatus.engine.input.sensor.BaseSensorData;

import java.util.Arrays;

public class OrientationData extends BaseSensorData{

    public static final float RAD_TO_DEG = 180.0f / (float) Math.PI;

    private final float[] _accelerometerValues = new float[3];
    private final float[] _magneticFieldValues = new float[3];
    private final float[] _rotationMatrix = new float[16];

    private int mMagneticFieldAccuracy;

    public OrientationData(final int pDisplayRotation){
        super(3, pDisplayRotation);
    }

    public float getRoll(){
        return super._Values[SensorManager.DATA_Z];
    }

    public float getPitch(){
        return super._Values[SensorManager.DATA_Y];
    }

    public float getYaw(){
        return super._Values[SensorManager.DATA_X];
    }

    @Override
    @Deprecated
    public void setValues(final float[] pValues){
        super.setValues(pValues);
    }

    @Override
    @Deprecated
    public void setAccuracy(final int pAccuracy){
        super.setAccuracy(pAccuracy);
    }

    public void setAccelerometerValues(final float[] pValues){
        System.arraycopy(pValues, 0, this._accelerometerValues, 0, pValues.length);
        this.updateOrientation();
    }

    public void setMagneticFieldValues(final float[] pValues){
        System.arraycopy(pValues, 0, this._magneticFieldValues, 0, pValues.length);
        this.updateOrientation();
    }

    private void updateOrientation(){
        SensorManager.getRotationMatrix(this._rotationMatrix, null, this._accelerometerValues, this._magneticFieldValues);

        switch (this._DisplayRotation){
            case Surface.ROTATION_0:
                break;
            case Surface.ROTATION_90:
                SensorManager.remapCoordinateSystem(this._rotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, this._rotationMatrix);
                break;
        }

        final float[] values = this._Values;
        SensorManager.getOrientation(this._rotationMatrix, values);

        for (int i = values.length - 1; i >= 0; i--){
            values[i] = values[i] * RAD_TO_DEG;
        }
    }

    public int getAccelerometerAccuracy(){
        return this.getAccuracy();
    }

    public void setAccelerometerAccuracy(final int pAccelerometerAccuracy){
        super.setAccuracy(pAccelerometerAccuracy);
    }

    public int getMagneticFieldAccuracy(){
        return this.mMagneticFieldAccuracy;
    }

    public void setMagneticFieldAccuracy(final int pMagneticFieldAccuracy){
        this.mMagneticFieldAccuracy = pMagneticFieldAccuracy;
    }

    @Override
    public String toString(){
        return "Orientation: " + Arrays.toString(this._Values);
    }
}
